package com.one.system.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.one.common.core.constants.Constants;
import com.one.common.core.domain.R;
import com.one.common.core.domain.TableDataInfo;
import com.one.common.core.enums.ResultCode;
import com.one.common.security.exception.ServiceException;
import com.one.system.domain.exam.ExamQuestion;
import com.one.system.domain.question.Question;
import com.one.system.domain.question.dto.QuestionAddDTO;
import com.one.system.domain.question.dto.QuestionEditDTO;
import com.one.system.domain.question.dto.QuestionQueryDTO;
import com.one.system.domain.question.es.QuestionES;
import com.one.system.domain.question.vo.QuestionDetailVO;
import com.one.system.domain.question.vo.QuestionVO;
import com.one.system.elasticsearch.QuestionRepository;
import com.one.system.manager.QuestionCacheManager;
import com.one.system.mapper.exam.ExamQuestionMapper;
import com.one.system.mapper.question.QuestionMapper;
import com.one.system.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        //在竞赛添加题目那个页面也调用这个接口
        //需要把已经选择了的题目在展示时排除掉
        //把题目id传过来，在sql中进行排除
        //没传题目id就正常执行后面的
        String excludeIdStr = questionQueryDTO.getExcludeIdStr();
        if (StrUtil.isNotEmpty(excludeIdStr)) {
            String[] excludeIdArr = excludeIdStr.split(Constants.SPLIT_SEM);
            Set<Long> excludeIdSet = Arrays.stream(excludeIdArr)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }
        //pagehelper帮助实现分页
        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        return  questionMapper.selectQuestionList(questionQueryDTO);
//        if(CollectionUtil.isEmpty(questionList)){
//            return TableDataInfo.empty();
//        }
//        //获取符合查询条件的数据总数
//        new PageInfo<>(questionList).getTotal();
//        return TableDataInfo.success(questionList,questionList.size());
    }

    @Override
    public int add(QuestionAddDTO questionAddDTO) {
        //判断一下数据的正确性，比如这个题目是否已经存在
        List<Question> list = questionMapper.selectList(new LambdaQueryWrapper<Question>().select()
                .eq(Question :: getTitle,questionAddDTO.getTitle()));
        if(CollectionUtil.isNotEmpty(list)){
            //不是空说明存在
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        //参数的效验也还可以在这里实现，也可以通过validation提供的注解，在dto那里实现
        //将DTO转换为实体类
        Question question = new Question();
        BeanUtil.copyProperties(questionAddDTO,question);
        //存入数据库之前也同步到es当中
        QuestionES questionES = BeanUtil.copyProperties(questionAddDTO, QuestionES.class);
        questionRepository.save(questionES);
        //更新redis，在切换题目功能中，redis当中维护了整个题目的顺序，添加和删除时需要维护题目顺序
        questionCacheManager.addCache(question.getQuestionId());
        return questionMapper.insert(question);
    }

    @Override
    public QuestionDetailVO detail(long questionId) {
        //根据题目标题查询题目详情
        Question question = isQuestionHave(questionId);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        isQuestionHave(questionEditDTO.getQuestionId());
        //让前端直接把所有信息全部传过来，不做哪个字段修改判断，全部整体修改
        Question oldQuestion = new Question();
        oldQuestion.setQuestionId(questionEditDTO.getQuestionId());
        oldQuestion.setTitle(questionEditDTO.getTitle());
        oldQuestion.setDifficulty(questionEditDTO.getDifficulty());
        oldQuestion.setContent(questionEditDTO.getContent());
        oldQuestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldQuestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldQuestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldQuestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldQuestion.setMainFunc(questionEditDTO.getMainFunc());
        //同步到es中
        QuestionES questionES = BeanUtil.copyProperties(oldQuestion, QuestionES.class);
        questionRepository.save(questionES);
        return questionMapper.updateById(oldQuestion);
    }

    @Override
    public int delete(long questionId) {
        Question question = isQuestionHave(questionId);
        //从es中删除
        QuestionES questionES = BeanUtil.copyProperties(question, QuestionES.class);
        questionRepository.delete(questionES);
        //更新redis
        questionCacheManager.deleteCache(questionId);

        examQuestionMapper.delete(new LambdaQueryWrapper<ExamQuestion>()
                .eq(ExamQuestion::getQuestionId,questionId));
        return questionMapper.deleteById(questionId);
    }

    private Question isQuestionHave(long questionId) {
        Question question =  questionMapper.selectById(questionId);
        if(BeanUtil.isEmpty(question)){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return question;
    }
}
